package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.util.Jwtutil;
import com.heima.common.util.MD5Utils;
import com.heima.model.admin.dtos.AdminLoginDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * @author 慕颖
 * @description 针对表【ad_user(管理员用户信息表)】的数据库操作Service实现
 * @createDate 2022-09-11 20:07:32
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser>
        implements AdUserService {

    /**
     * 登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(AdminLoginDto dto) {
        if (dto != null) {
            LambdaQueryWrapper<AdUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(AdUser::getName, dto.getName());
            AdUser adUser = getOne(wrapper);
            String pwd = MD5Utils.encodeWithSalt(dto.getPassword(), adUser.getSalt());
            if (pwd.equals(adUser.getPassword())) {
                //验证通过颁发令牌
                HashMap<String, Object> adMap = new HashMap<>();
                adMap.put("id", adUser.getId());
                adMap.put("name", adUser.getName());
                adMap.put("password", adUser.getPassword());
                String token = Jwtutil.token(adMap);
                // 封装响应数据 map+token
                HashMap<String, Object> resp = new HashMap<>();
                resp.put("user", adMap);
                resp.put("token", token);
                // 响应前端
                System.out.println("用户用户111");
                return ResponseResult.okResult(resp);
            } else {
                return ResponseResult.error(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        } else {
            return ResponseResult.error(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
    }
}




